class UserController < ApplicationController
  before_filter :login_required, :only => ['edit','home']
  skip_before_filter :verify_authenticity_token, :only =>
    [:auto_complete_for_user_ident]
  auto_complete_for :user,:ident
  

  def signup
    if request.post?
      @user = User.new(params[:user])
      if @user.save
        session[:user]=User.auth(@user.ident,@user.pwd)
        flash[:message] = "Signup successful"
        redirect_to :action => 'home'
      else
        flash[:warning] = "Signup unsuccessful"
      end
    end
  end

  def login
    @users=User.all(:order => "ident")
    @idents=@users.collect {|u| u.ident}
    if request.post?
      if session[:user]=User.auth(params[:user][:ident],params[:user][:pwd])
        flash[:message] = "Login successful"
        redirect_to :action=> 'home'
      else
        flash[:warning] = "Login unsuccessful"
      end
    end        
  end

  def logout
    session[:user]=nil
    flash[:message]="Logged out"
    redirect_to :action => 'login'
  end

  def delete
  end

  def edit
    if request.post? 
      opwd=params[:user][:opwd]
      n1=params[:user][:npwd1]
      n2=params[:user][:npwd2]
      puts "#{current_user.pwd}:#{opwd}:#{n1}:#{n2}"
      if(opwd!=current_user.pwd) then 
        flash[:warning]="Wrong password!"
      else
        if(n1!=n2) then 
          flash[:warning]="New password not match!"
        else
          current_user.pwd=n1
          current_user.save
          flash[:message]="Password changed!"
          redirect_to :action => 'home'
        end
      end
    end
  end

  def forget
    
  end

  def home
    @labs = Lab.all(:order => 'id')
    @user = User.find(current_user.id)
    @scores = @user.scores.sort_by {|x| x.lab_id}
    
    @list = []
    
    @labs.zip(@scores) do |l,s|
      @list<<[l,s]
    end
    
    render :layout => "async"
  end

end
